

class ProjectController extends BaseController{
    def beforeInterceptor = [action:this.auth]
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        session.language = "sv"
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        [ projectInstanceList: Project.list( params ), projectInstanceTotal: Project.count() ]
    }

    def show = {
        def projectInstance = Project.get( params.id )

        if(!projectInstance) {
            flash.message = "Project not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            
            // test if the project is available in current mode
            if(((session.mode==null || session.mode.equalsIgnoreCase("sandbox")) && projectInstance.mode==1) || (session.mode != null && (session.mode.equalsIgnoreCase("budget")) && projectInstance.mode==0) || projectInstance.mode==2){
                // If the project mode corresponds to the current mode
                return [
                    projectInstance : projectInstance,
                    numberOfEmployees: projectInstance.getListOfEmployees().size()
                ]
            }
            else{
                flash.message = "Project not accessible in current mode"
                redirect(action:list)
            }

        }
    }

    def delete = {
            //System.out.println(params.id)
            def projectInstance = Project.get( params.id )
            if(projectInstance) {
                try {
                    if(session.mode != null && session.mode.equalsIgnoreCase("budget")){ // if budget mode: delete the project
                        projectInstance.delAllEmployees()
                        projectInstance.delete(flush:true)
                        flash.message = "Project ${params.id} deleted"
                        redirect(action:list)
                    }
                    else{ // if sandbox mode, update the mode of the project
                        if(projectInstance.mode==1){ // if visible in sandbox only: delete the project
                            projectInstance.delAllEmployees()
                            projectInstance.delete(flush:true)
                            flash.message = "Project ${params.id} deleted"
                            redirect(action:list)
                        }
                        else{ //if visible in budget too, just make it invisible for sandbox
                          redirect(action:deleteSandboxMode,id:params.id)                          
                        }
                    }
                }
                catch(org.springframework.dao.DataIntegrityViolationException e) {
                    flash.message = "Project ${params.id} could not be deleted"
                    redirect(action:show,id:params.id)
                }
            }
            else {
                flash.message = "Project not found with id ${params.id}"
                redirect(action:list)
            }
        
    }

    def edit = {
        def projectInstance = Project.get( params.id )

        if(!projectInstance) {
            flash.message = "Project not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ projectInstance : projectInstance ]
        }
    }

    def update = {
        def projectInstance = Project.get( params.id )
        if(projectInstance) {
            if(params.version) {
                def version = params.version.toLong()
                if(projectInstance.version > version) {

                    projectInstance.errors.rejectValue("version", "project.optimistic.locking.failure", "Another user has updated this Project while you were editing.")
                    render(view:'edit',model:[projectInstance:projectInstance])
                    return
                }
            }
            projectInstance.properties = params
            if(!projectInstance.hasErrors() && projectInstance.save()) {
                flash.message = "Project ${projectInstance} updated"
                redirect(action:show,id:projectInstance.id)
            }
            else {
                render(view:'edit',model:[projectInstance:projectInstance])
            }
        }
        else {
            flash.message = "Project not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def deleteSandboxMode = {
        def projectInstance = Project.get( params.id )
        if(projectInstance) {
            if(params.version) {
                def version = params.version.toLong()
                if(projectInstance.version > version) {

                    projectInstance.errors.rejectValue("version", "project.optimistic.locking.failure", "Another user has updated this Project while you were editing.")
                    render(view:'edit',model:[projectInstance:projectInstance])
                    return
                }
            }
            projectInstance.properties = params
            projectInstance.mode=0
            projectInstance.delAllEmployeesMode(1)
            if(!projectInstance.hasErrors() && projectInstance.save()) {
                flash.message = "Project ${projectInstance} deleted from sandbox mode only"
                redirect(action:list)
            }
            else {
                render(view:'edit',model:[projectInstance:projectInstance])
            }
        }
        else {
            flash.message = "Project not found with id ${params.id}"
            redirect(action:list)
        }
    }


    def create = {
        def projectInstance = new Project()
        projectInstance.properties = params
        return ['projectInstance':projectInstance]
    }

    def save = {
        if(params.mode.equalsIgnoreCase("budget")){
            params.mode=2
        }
        else{
            params.mode=1
        }
        def projectInstance = new Project(params)

        if(!projectInstance.hasErrors() && projectInstance.save()) {
            flash.message = "Project ${projectInstance} created"
            redirect(action:show,id:projectInstance.id)
        }
        else {
            render(view:'create',model:[projectInstance:projectInstance])
        }
    }

    def add_employee = {
        def p = Project.get(params.id);
        ArrayList l = new ArrayList();
            // test if the project is available in current mode
            if(((session.mode==null || session.mode.equalsIgnoreCase("sandbox")) && p.mode==1) || (session.mode != null && (session.mode.equalsIgnoreCase("budget")) && p.mode==0) || p.mode==2){
                // If the project mode corresponds to the current mode
                for(Employee e : Employee.list()){
                    
                    int wantedMode
                    if(session.mode == null || session.mode.equalsIgnoreCase("sandbox")){ // if current mode = sandbox
                       wantedMode=1  
                    }
                    else{   // if current mode = budget
                        wantedMode=0
                    }

                    //TODO Modification in order to avoid employee from other container to show up there
                    if(!p.getListOfEmployeesByMode(wantedMode).contains(e)){
                        l.add(e);
                    }
                }
                render(view:'add_employee',model:[ employeeList: l, projectid: params.id ])
            }
            else{
                flash.message = "Project not accessible in current mode"
                redirect(action:list)
            }

        
    }

    def save_added_employee = {
        String[] vals = request.getParameterValues("employeeid")
        def projectInstance = Project.get(params.projectid)
        if (projectInstance) {
            for(String v : vals){
                def employee = Employee.get(v);
                if(employee == null) {
                    System.out.println(v + " fel!");
                }
                else{
                    // add information about the mode
                    int addMode
                    if(session.mode == null || session.mode.equalsIgnoreCase("sandbox")){
                        addMode=1
                    }
                    else{
                        addMode=0
                    }
                    projectInstance.addEmployee(employee,addMode);
                }
            }
            if(projectInstance.save(flush:true,validate:false)) {
                if(vals.length>1){
                    flash.message = "New employees added"
                }
                else{
                    flash.message = "New employee added"
                }
            }
            else{
                flash.message = "Cannot add new employee"

                projectInstance.errors.each {
                    println (it);
                }


            }
            redirect(action:show, id : params.projectid)
        }
        else{
            flash.message = "Project \"${projectInstance.name}\" not found with id ${params.projectid}"
            redirect(action:list)
        }

    }
    def delete_employee = {
        int wantedMode
        if(session.mode == null || session.mode.equalsIgnoreCase("sandbox")){ // if current mode = sandbox
           wantedMode=1
        }
        else{   // if current mode = budget
            wantedMode=0
        }
        List<Employee> l = Project.get(params.id).getListOfEmployeesByMode(wantedMode)
        
        [ employeeList: l, id: params.id ]
    }

    def save_deleted_employee = {
        String[] del = request.getParameterValues("employeeid")
        def projectInstance = Project.get(params.id)
        int delMode
        if(session.mode == null || session.mode.equalsIgnoreCase("sandbox")){
            delMode=1 //sandbox Mode
        }
        else{
            delMode=0 // budget Mode
        }
        for(String x : del){
             // add information about the mode
            projectInstance.delEmployee(Employee.get(x),delMode)


        }
        flash.message = "Employees deleted from the project"
        redirect(action:show, id : params.id)
    }

    def updateIncome = {
        Float newIncome = Float.parseFloat(params.figure);

        def projectInstance = Project.get(params.id);

        Budget b = projectInstance?.currentBudget();

        if(params.typeOfIncome == "expectedIncome"){
            b.expectedTotalIncome = newIncome;
        }
        else{
             b.knownTotalIncome = newIncome;
        }
        if(projectInstance.save(flush:true)){
                
        }
        else{
             projectInstance.errors.each {
                  println(it);
                }
                b.errors.each {
                 println(it);
                }
        }

        redirect(action:blank);
        
    }

    def changeMode = {
        //System.out.println("-"+session.mode+"-")
        Date d = new Date()
        if((session.mode==null)||(!session.mode.equalsIgnoreCase("budget"))){
              session.mode="budget"
        }
        else{
            session.mode="sandbox"
        }
        //System.out.println("-"+session.mode+"-")

        flash.message = "Mode changed"
        if(params.idProject.equals("null")){
            redirect(controller:params.currentController,action:params.currentView)
        }
        else{
            redirect(controller:params.currentController,action:params.currentView, id:params.idProject)
        }
    }

    def blank = {}
    
}
